package com.tomato.modules.id.controller;

import com.tomato.base.core.dto.SingleResponse;
import com.tomato.modules.id.runner.IdGeneratorRunner;
import com.tomato.modules.id.strategy.IdGeneratorStrategyService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 分布式 ID
 *
 * @author lizhifu
 * @date 2022/3/17
 */
@RestController
public class IdGenController {
    @Resource
    private IdGeneratorRunner idGeneratorRunner;
    @RequestMapping(value = "/api/id/get/{bizType}")
    public SingleResponse<Long> getId(@PathVariable("bizType") String bizType) {
        IdGeneratorStrategyService idGeneratorStrategyService = idGeneratorRunner.getGenerators(bizType);
        if(idGeneratorStrategyService == null){
            return SingleResponse.buildFailure(HttpStatus.BAD_REQUEST.toString(),"不存在的业务类型");
        }
        Long nextId = idGeneratorStrategyService.nextId();
        return SingleResponse.of(nextId);
    }
    @RequestMapping(value = "/api/id/snow/get/{bizType}/{workerId}")
    public SingleResponse<Long> getIdSnowFlake(@PathVariable("bizType") String bizType,@PathVariable("workerId") long workerId) {
        IdGeneratorStrategyService idGeneratorStrategyService = idGeneratorRunner.getGenerators(bizType+"_"+workerId);
        if(idGeneratorStrategyService == null){
            return SingleResponse.buildFailure(HttpStatus.BAD_REQUEST.toString(),"不存在的业务类型");
        }
        Long nextId = idGeneratorStrategyService.nextId();
        return SingleResponse.of(nextId);
    }
}
